<template>
  <a-select
    :ref="isRef ? (e) => getRef(e, isRefName) : ''"
    v-model:value="state.value"
    :loading="state.loading"
    :class="styleClass"
    :placeholder="prompt"
    :options="state.data"
    @change="onChange"
    @focus="onFocus"
  >
    <template v-if="state.loading" #notFoundContent>
      <a-spin size="small" />
    </template>
  </a-select>
</template>

<script setup>
/**
 * @name:SelectItem 选择常用字典
 */
import { reactive, watch, onMounted, nextTick } from 'vue'
import { post } from '@/utils/request'

const state = reactive({
  data: [],
  loading: false
})
const emit = defineEmits(['change', 'update:value', 'success'])

const props = defineProps({
  value: {
    type: [String, Number, Array],
    default: ''
  },
  valueKey: {
    type: String,
    default: 'dictItemCode'
  },
  trigger: {
    desc: '请求数据时机init:初始化/focus:聚焦',
    type: String,
    default: 'init'
  },
  type: {
    type: String,
    required: true,
    default: ''
  },
  params: {
    type: Object,
    default: () => ({})
  },
  defaultSelect: {
    type: String,
    default: ''
  },
  selectFirst: {
    type: Boolean,
    default: false
  },
  prompt: {
    type: String,
    default: '请选择'
  },
  styleClass: {
    type: String,
    default: 'min-w-[160px]'
  },
  isRef: {
    desc: '是否返回ref',
    type: Boolean,
    default: false
  },
  isRefName: {
    desc: 'ref名称',
    type: String,
    default: ''
  }
})
watch(
  () => props.value,
  () => {
    state.value = props.value || null
    if (!props.value && props.selectFirst && state.data[0]) {
      state.value = state.data[0].value
      emit('update:value', state.value)
    }
  },
  {
    immediate: true
  }
)
const onChange = (record, option) => {
  emit('change', record, option)
  emit('update:value', record)
}
//获取数据
const getData = async () => {
  state.data = []
  state.loading = true
  const { data = [], code } = await post('/operation/opex/getDictCommonItemList', { dictCommonCode: props.type, status: 1, ...props.params })
  if (code === 0) {
    state.data = data.map((item) => {
      return {
        label: item.dictItemName,
        value: item[props.valueKey]
      }
    })
    state.loading = false
    if (props.defaultSelect) {
      state.value = props.defaultSelect
      emit('update:value', state.value)
    }
    if (props.selectFirst) {
      state.value = state.data[0].value
      emit('update:value', state.value)
    }
  }
}

const getRef = (e, name) => {
  nextTick(() => {
    emit('success', e, name)
  })
}
const onFocus = () => {
  props.trigger === 'focus' && getData()
}
onMounted(() => {
  props.trigger === 'init' && getData()
})
</script>
<style lang="less" scoped></style>
